package com.yangli.leecode.a;

import com.yangli.ahies.study.util.ListNode;


/**
 * @author ly
 * @description https://leetcode-cn.com/problems/add-two-numbers/
 * 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
 * 你将两个数相加，并以相同形式返回一个表示和的链表。
 * 你可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 * @data 2022/4/18
 */
public class AddTwoNumbers {
    private static final System.Logger LOGGER = System.getLogger("AddTwoNumbers");

    public static void main(String[] args) {
        LOGGER.log(System.Logger.Level.INFO, "Run!");

        AddTwoNumbers addTwoNumbers = new AddTwoNumbers();
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(3, l1);
        ListNode l3 = new ListNode(4, l2);

        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5, l4);
        ListNode l6 = new ListNode(6, l5);

        System.out.println(addTwoNumbers.addTwoNumbers(l3, l6));

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0; //进位
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }

            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }
}
